//
//  StatusPictureView.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/16.
//  Copyright © 2015年 余丽丽. All rights reserved.
//配图视图

import UIKit
import SDWebImage

//点击照片发出的通知名
let statusSelectImgNotification = "statusSelectImgNotification"
//URL的KEY
let statusSelectImgURLKey = "statusSelectImgURLKey"
//记录 Indexpath 的KEY
let statusSelectImgIndexpathKey = "statusSelectImgIndexpathKey"


//cell可重用的标志
private let statusPictureViewCellID = "pictureViewCell"

class StatusPictureView: UICollectionView {

    // 流水布局
    let pictureLayout = UICollectionViewFlowLayout()
    
    var status :Status?{
    
        didSet{
            //自动布局
            sizeToFit()
            //刷新视图
            reloadData()
        }
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        //设置背景色
        backgroundColor = UIColor.clearColor()
        
        //注册cell
        registerClass(statusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellID)
        
        //设置代理,让自己当自己的数据源代理和代理
        self.delegate = self
        self.dataSource = self
        
        
    }
    // TODO:| 返回size
    // 执行sizeToFit()方法会自动调用此方法,所以可以在这里设置流水布局
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
        
    }
    
    //计算视图大小
    private func calcViewSize() -> CGSize {
    
        let margin :CGFloat = 10
        let Imgwidth :CGFloat = (UIScreen.mainScreen().bounds.size.width - 2 * margin - statusCellControlMargin * 2 ) / 3
        let ImgeSize = CGSize(width: Imgwidth, height: Imgwidth)
        
        
        
        //设置流水布局中item对象的size
        pictureLayout.itemSize = ImgeSize
        
        // 获取图片的个数
        let imgCount = status?.pic_urls?.count ?? 0
        
        
        
        switch imgCount {
            
        case 0:
            return CGSizeZero
        case 1:
            return ImgeSize
        case 4:
            return CGSize(width: Imgwidth * 2 + margin, height: Imgwidth * 2 + margin)
        default :
            let row = CGFloat((imgCount + 2) / 3)
            return CGSize(width: UIScreen.mainScreen().bounds.size.width - 2 * statusCellControlMargin, height: row * Imgwidth + (row - 1) * margin)
        }

    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    
   }

// 在 swift 中 ,协议同样可以通过 extension 来写
extension StatusPictureView: UICollectionViewDelegate, UICollectionViewDataSource {
    
    
    func cellRectAtIndexPath(indexPath:NSIndexPath) -> CGRect{
        
        let cell = self.cellForItemAtIndexPath(indexPath) as! statusPictureViewCell
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
    }

    //选中cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! statusPictureViewCell
        PushfromView.image = cell.iconView.image
        PushfromRect = cellRectAtIndexPath(indexPath)
        PopToViewSuper = self
        
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(statusSelectImgNotification, object: self, userInfo: [statusSelectImgURLKey:status!.pic_largeUrls!, statusSelectImgIndexpathKey:indexPath])
 
    }
    
    //返回cell的个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pic_urls?.count ?? 0
    }
    
    //返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // DOTO:| 自定义cell
        let cell = dequeueReusableCellWithReuseIdentifier(statusPictureViewCellID, forIndexPath: indexPath) as! statusPictureViewCell
        // 小图
        cell.imgUrl = NSURL(string: (status?.pic_urls![indexPath.row])! as! String)
        // 大图
        //cell.imgUrl = NSURL(string: (status?.pic_largeUrls![indexPath.row])! as! String)
        // 中图
        //cell.imgUrl = NSURL(string: (status?.pic_bmiddleUrls![indexPath.row])! as! String)
        cell.contentView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return cell
        
    }
    
   
    
   
}

// 自定义cell 改变图片的填充方式
class statusPictureViewCell: UICollectionViewCell{

    var imgUrl: NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imgUrl)
            
            //判断是否是gif
            gifIcon.hidden = (imgUrl!.pathExtension != "gif")
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
    
        contentView.addSubview(iconView)
        iconView.addSubview(gifIcon)
        
        iconView.ff_Fill(contentView)
        gifIcon.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
        
    }

    private lazy var iconView: UIImageView = {
    
        let img = UIImageView()
        img.contentMode = UIViewContentMode.ScaleAspectFill
        //超出边界部分直接减掉
        img.clipsToBounds = true
        return img
    
    }()
    
    //gif图标
    private lazy var gifIcon:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))

}
